package com.springboot.demo.mq;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.connection.MessageListener;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.nio.charset.StandardCharsets;

/**
 * @Description：
 * @Date： Created in 2022/1/5
 * @author： jianbin.lei
 * @Auto： <a href="mailto:493168771@qq.com">jianbin.lei</a>
 */
@Service
public class MessageSubscriber {

    Logger logger = LogManager.getLogger(MessageSubscriber.class.getName());

    private static String CHANNEL = "dididispace";

    public MessageSubscriber(RedisTemplate redisTemplate) {
        RedisConnection redisConnection = redisTemplate.getConnectionFactory().getConnection();
        redisConnection.subscribe(new MessageListener() {
            @Override
            public void onMessage(Message message, byte[] bytes) {
                // 收到消息的处理逻辑
                logger.info("Receive message : " + message);
            }
        }, CHANNEL.getBytes(StandardCharsets.UTF_8));
    }
}
